import Vue from 'vue';
import axios from 'axios';
import router from '../router';
import store from '@/store/store.js';
// eslint-disable-next-line no-unused-vars

//是否允许跨域
axios.defaults.withCredentials = true;//允许携带cookies信息
// axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const instance = axios.create({
    // baseURL: "http://clound_clothing.wenkangkeji.com/mlcc",//请求URL前缀
    // baseURL: "https://api.nbyid.cn/mlcc",//请求URL前缀
    // baseURL: "http://192.168.0.115:8080/mlcc",//请求URL前缀
    baseURL: "http://localhost:8080/mlcc",//请求URL前缀
    timeout: 30000,//超时时间
    headers: {//即将被发送的自定义请求头

    }
});

//请求拦截器
instance.interceptors.request.use(config => {
    // config.headers.common['Authorization'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDIwNTE5MTEsInVzZXJuYW1lIjoiMTMyNzE4NjE1MjUifQ.vCuubSm1XAt-eHo4EA_BlKuU5b-k77nGxPgOrK1BXaY';
    //在发送请求之前做某事
    if (store.getters.isLogin) {
        // config.headers.common['Authorization'] = store.state.token;
        // config.headers.common['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDA3NTg5NzEsInVzZXJuYW1lIjoiMTMyNzE4NjE1MjUifQ.2pDO4tyZejYWpDk6A7hzuKZfJs3FjQBtK1efKKTo8Sk';
        startLoading();
    }
    return config;
}, error => {
    //请求错误时做某事
    return Promise.reject(error);
});

//响应拦截器
instance.interceptors.response.use(response => {
    if (store.getters.isLogin) {
        endLoading();
    }
    return response;
}, error => {
    if (error.response && error.response.status == 400) {
        //语义有误，当前请求无法被服务器理解。除非进行修改，否则客户端不应该重复提交这个请求
        //请求参数有误。
        Vue.prototype.$message({
            message: error.response.data,
            type: 'error'
        })
        endLoading();
    }
    if (error.response && error.response.status == 401) {
        //未经授权的
        //token验证失败专用
        Vue.prototype.$message({
            message: error.response.data,
            type: 'error'
        })
        endLoading();
        store.commit('loginOut');
    }
    if (error.response && error.response.status == 403) {
        //服务器已经理解请求，但是拒绝执行它
        Vue.prototype.$message({
            message: error.response.data,
            type: 'error'
        })
        endLoading();
    }
    if (error.response && error.response.status == 404) {
        router.push('/404.vue');
    }


    return Promise.reject(error);
});

export default instance

// eslint-disable-next-line no-unused-vars
let loading;

function startLoading() {
    // loading = Loading.Loading.service({
    //     lock: true,
    //     text: '加载中……',
    //     background: 'rgba(0, 0, 0, 0.7)'
    // })
}

function endLoading() {
    // loading.close()
}
